﻿Imports AugmentLib.Database
Imports System.Configuration.ConfigurationManager
Imports AugmentLib.InputOutput.Encryption
Imports AugmentLib.WebComponent

Partial Class AnnouncementEntry
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Session("StaffId") Is Nothing Then
            Response.Redirect("Default.aspx")
        ElseIf Session.Item("StaffType").ToString = "2" Then
            Response.Redirect("Default.aspx")
        Else
            lblStaffUID.Text = Session("StaffId").ToString
        End If

        If Not Page.IsPostBack Then

            CBEBack.ConfirmText = "You are about to navigate away from this page. " & vbCrLf & "Changes will be discard!"

            If Not Request.QueryString("id") Is Nothing Then
                lblAnnouncementUID.Text = SymmetricDecryptFromHex(Request.QueryString("id"), "augment")
                LoadAnnouncement(lblAnnouncementUID.Text)
            End If

        End If
    End Sub

    Private Sub LoadAnnouncement(ByVal AnnouncementID As String)
        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        Dim TempDT As New Data.DataTable
        Try
            objDB.OpenConnection()

            objDB.dbVariable.SQLString = "SELECT Title, Priority, Content, Attachment, AttDesc FROM AW_Announcement WHERE AnnouncementId=@AnnouncementID"
            objDB.AddParameter("AnnouncementID", Data.SqlDbType.UniqueIdentifier, New Guid(AnnouncementID))
            objDB.FillData(TempDT, "AW_Announcement", Database.SQLCommandType.NormalString)

            For Each ReadRow As Data.DataRow In TempDT.Rows
                txtTitle.Text = ReadRow.Item("Title").ToString
                ddlPriority.SelectedValue = ReadRow.Item("Priority").ToString
                txtContent.Text = ReadRow.Item("Content").ToString
                If ReadRow.Item("Attachment").ToString = "" Then
                    lnkAttachment.Visible = False
                    filAttachment.Visible = True
                    imgDel.Visible = False
                Else
                    lnkAttachment.Visible = True
                    filAttachment.Visible = False
                    imgDel.Visible = True
                    lnkAttachment.Text = ReadRow.Item("Attachment").ToString
                End If
                txtAttDesc.Text = ReadRow.Item("AttDesc").ToString
            Next

            objDB.dbVariable.SQLString = "SELECT a.StaffId, b.Initial FROM AW_AnnouncementToList a LEFT JOIN AW_Staff b " & _
                                        "ON a.staffId = b.StaffId WHERE AnnouncementId=@AnnouncementID"
            objDB.AddParameter("AnnouncementID", Data.SqlDbType.UniqueIdentifier, New Guid(AnnouncementID))
            objDB.FillData(TempDT, "AW_AnnouncementToList", Database.SQLCommandType.NormalString)

            Dim strSelected As String = String.Empty
            Dim strSelectedValue As String = String.Empty

            For Each ReadRow As Data.DataRow In TempDT.Rows
                If strSelected = "" Then
                    strSelected = ReadRow.Item("Initial").ToString
                Else
                    strSelected += ", " & ReadRow.Item("Initial").ToString
                End If
                If strSelectedValue = "" Then
                    strSelectedValue = ReadRow.Item("StaffId").ToString
                Else
                    strSelectedValue += "«" & ReadRow.Item("StaffId").ToString
                End If
            Next
            lblTolist.Text = strSelectedValue
            txtTolist.Text = strSelected

        Catch
            divError.Visible = True
            lblMsgError.Text = "Error getting data from Database."
            Return
        Finally
            If (objDB IsNot Nothing) Then
                objDB.CloseConnection()
            End If
        End Try
    End Sub

    Private Sub ClearAllFields()
        txtTolist.Text = String.Empty
        txtTitle.Text = String.Empty
        txtContent.Text = String.Empty
        txtAttDesc.Text = String.Empty
        ddlPriority.SelectedValue = "3"
        lnkAttachment.Text = String.Empty
        filAttachment.Visible = True
        lnkAttachment.Visible = False
    End Sub

    Protected Sub BtnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))

        If lblAnnouncementUID.Text = "" Then
            'Insert 
            Dim Uploaded As String = ""
            Try
                If filAttachment.HasFile Then
                    Dim Attachment As HttpPostedFile = filAttachment.PostedFile
                    Dim objAttComp As New ImageComp
                    Uploaded = objAttComp.UploadAnyFile(Attachment, "attachment")
                End If
            Catch ex As Exception
                lblMsgError.Text = ex.Message
                divError.Visible = True
                Exit Sub
            End Try

           Try
                objDB.OpenConnection()
                'Added by minginn @ 9/4/11 Transaction to also insert scaling commission to the database
                objDB.InitDbTrans()
                objDB.dbVariable.SQLString = "INSERT INTO AW_Announcement (AnnouncementId, Title, Priority, Content, Attachment, CreateBy, " & _
                                            "AttDesc, UpdateBy, CreateDate, UpdateDate, StatusDelete) Values (@AnnouncementId, " & _
                                            "@Title, @Priority, @Content, @Attachment, @CreateBy, @AttDesc, @UpdateBy, @CreateDate, @UpdateDate, @StatusDelete)"
                lblAnnouncementUID.Text = Guid.NewGuid.ToString
                objDB.AddParameter("AnnouncementId", Data.SqlDbType.UniqueIdentifier, New Guid(lblAnnouncementUID.Text))
                objDB.AddParameter("Title", Data.SqlDbType.NVarChar, txtTitle.Text.Trim)
                objDB.AddParameter("Priority", Data.SqlDbType.TinyInt, ddlPriority.SelectedValue)
                objDB.AddParameter("Content", Data.SqlDbType.NVarChar, txtContent.Text.Trim)
                If Uploaded = "" Then
                    objDB.AddParameter("Attachment", Data.SqlDbType.NVarChar, DBNull.Value)
                Else
                    objDB.AddParameter("Attachment", Data.SqlDbType.NVarChar, Uploaded)
                End If
                If txtAttDesc.Text = "" Then
                    objDB.AddParameter("AttDesc", Data.SqlDbType.NVarChar, DBNull.Value)
                Else
                    objDB.AddParameter("AttDesc", Data.SqlDbType.NVarChar, txtAttDesc.Text.Trim)
                End If
                objDB.AddParameter("CreateBy", Data.SqlDbType.UniqueIdentifier, New Guid(lblStaffUID.Text))
                objDB.AddParameter("UpdateBy", Data.SqlDbType.UniqueIdentifier, DBNull.Value)
                objDB.AddParameter("UpdateDate", Data.SqlDbType.DateTime, DBNull.Value)
                objDB.AddParameter("CreateDate", Data.SqlDbType.DateTime, Now)
                objDB.AddParameter("StatusDelete", Data.SqlDbType.TinyInt, 0)
                objDB.ExecuteQuery()
                objDB.ClearParameter()
                Dim tolist() As String
                tolist = lblTolist.Text.Split("«")
                For Each strTo As String In tolist
                    objDB.dbVariable.SQLString = "INSERT INTO AW_AnnouncementToList (AnnouncementId, StaffId) " & _
                                                "Values (@AnnouncementId, @StaffId)"
                    objDB.AddParameter("AnnouncementId", Data.SqlDbType.UniqueIdentifier, New Guid(lblAnnouncementUID.Text))
                    objDB.AddParameter("StaffId", Data.SqlDbType.UniqueIdentifier, New Guid(strTo))
                    objDB.ExecuteQuery()
                Next
                objDB.DbTransCommit()
                objDB.CloseConnection()
                Session.Add("SavedAnnouce", "Y")
                Response.Redirect("AnnouncementList.aspx", True)
            Catch ex As Exception
                If objDB.dbVariable.objConn.State = Data.ConnectionState.Open Then
                    objDB.DbTransRollback()
                    objDB.CloseConnection()
                End If
                If Uploaded <> "" Then
                    Dim objAttComp As New ImageComp
                    objAttComp.DeleteSingleFile("attachment", Uploaded)
                End If
                lblAnnouncementUID.Text = ""
                lblMsgError.Text = ex.Message
                divError.Visible = True
            End Try
        Else
            'Update 
            Dim Uploaded As String = ""
            Try
                If filAttachment.HasFile Then
                    Dim Attachment As HttpPostedFile = filAttachment.PostedFile
                    Dim objAttComp As New ImageComp
                    Uploaded = objAttComp.UploadAnyFile(Attachment, "attachment")
                End If
            Catch ex As Exception
                lblMsgError.Text = ex.Message
                divError.Visible = True
                Exit Sub
            End Try

            Try
                objDB.OpenConnection()
                objDB.InitDbTrans()
                objDB.dbVariable.SQLString = "DELETE FROM AW_AnnouncementToList WHERE AnnouncementId=@AnnouncementId"
                objDB.AddParameter("AnnouncementId", Data.SqlDbType.UniqueIdentifier, New Guid(lblAnnouncementUID.Text))
                objDB.ExecuteQuery()
                objDB.dbVariable.SQLString = "UPDATE AW_Announcement SET Title=@Title, Priority=@Priority, Content=@Content, " & _
                                        "Attachment=@Attachment, AttDesc=@AttDesc, UpdateBy=@UpdateBy, UpdateDate=@UpdateDate WHERE AnnouncementId=@AnnouncementId"
                objDB.AddParameter("AnnouncementId", Data.SqlDbType.UniqueIdentifier, New Guid(lblAnnouncementUID.Text))
                objDB.AddParameter("Title", Data.SqlDbType.NVarChar, txtTitle.Text.Trim)
                objDB.AddParameter("Priority", Data.SqlDbType.TinyInt, ddlPriority.SelectedValue)
                objDB.AddParameter("Content", Data.SqlDbType.NVarChar, txtContent.Text.Trim)
                If Uploaded = "" Then
                    If lnkAttachment.Text <> "" Then
                        objDB.AddParameter("Attachment", Data.SqlDbType.NVarChar, lnkAttachment.Text)
                    Else
                        objDB.AddParameter("Attachment", Data.SqlDbType.NVarChar, DBNull.Value)
                    End If
                Else
                    objDB.AddParameter("Attachment", Data.SqlDbType.NVarChar, Uploaded)
                End If
                If txtAttDesc.Text = "" Then
                    objDB.AddParameter("AttDesc", Data.SqlDbType.NVarChar, DBNull.Value)
                Else
                    objDB.AddParameter("AttDesc", Data.SqlDbType.NVarChar, txtAttDesc.Text.Trim)
                End If
                objDB.AddParameter("UpdateBy", Data.SqlDbType.UniqueIdentifier, New Guid(lblStaffUID.Text))
                objDB.AddParameter("UpdateDate", Data.SqlDbType.DateTime, Now())
                objDB.ExecuteQuery()
                Dim tolist() As String
                tolist = lblTolist.Text.Split("«")
                For Each strTo As String In tolist
                    objDB.dbVariable.SQLString = "INSERT INTO AW_AnnouncementToList (AnnouncementId, StaffId) " & _
                                                "Values (@AnnouncementId, @StaffId)"
                    objDB.AddParameter("AnnouncementId", Data.SqlDbType.UniqueIdentifier, New Guid(lblAnnouncementUID.Text))
                    objDB.AddParameter("StaffId", Data.SqlDbType.UniqueIdentifier, New Guid(strTo))
                    objDB.ExecuteQuery()
                Next
                objDB.DbTransCommit()
                objDB.CloseConnection()
                Session.Add("SavedAnnouce", "Y")
                Response.Redirect("AnnouncementList.aspx", True)
            Catch ex As Exception
                If objDB.dbVariable.objConn.State = Data.ConnectionState.Open Then
                    objDB.DbTransRollback()
                    objDB.CloseConnection()
                End If
                If Uploaded <> "" Then
                    Dim objAttComp As New ImageComp
                    objAttComp.DeleteSingleFile("attachment", Uploaded)
                End If
                lblMsgError.Text = ex.Message
                divError.Visible = True
                Exit Sub
            Finally
                If (objDB IsNot Nothing) Then
                    objDB.CloseConnection()
                End If
            End Try
        End If
    End Sub

    Protected Sub lnkAttachment_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles lnkAttachment.Click
        'Open for save attachment
        Dim path As String = Server.MapPath("attachment/" & lnkAttachment.Text) 'get file object as FileInfo
        Dim file As System.IO.FileInfo = New System.IO.FileInfo(path) '-- if the file exists on the server
        If file.Exists Then 'set appropriate headers
            Response.Clear()
            Response.AddHeader("Content-Disposition", "attachment; filename=" & file.Name)
            Response.AddHeader("Content-Length", file.Length.ToString())
            Response.ContentType = "application/octet-stream"
            Response.WriteFile(file.FullName)
            Response.End() 'if file does not exist
        Else
            lblMsgError.Text = "This file does not exist!"
            divError.Visible = True
        End If 'nothing in the URL as HTTP GET
    End Sub

    Protected Sub imgDel_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgDel.Click
        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        Try
            objDB.OpenConnection()
            objDB.InitDbTrans()
            objDB.dbVariable.SQLString = "UPDATE AW_Announcement SET Attachment=@Attachment, AttDesc=@AttDesc, UpdateBy=@UpdateBy, UpdateDate=@UpdateDate WHERE AnnouncementId=AnnouncementId"
            objDB.AddParameter("AnnouncementId", Data.SqlDbType.UniqueIdentifier, New Guid(lblAnnouncementUID.Text))
            objDB.AddParameter("Attachment", Data.SqlDbType.NVarChar, DBNull.Value)
            objDB.AddParameter("AttDesc", Data.SqlDbType.NVarChar, DBNull.Value)
            objDB.AddParameter("UpdateBy", Data.SqlDbType.UniqueIdentifier, New Guid(lblStaffUID.Text))
            objDB.AddParameter("UpdateDate", Data.SqlDbType.DateTime, Now())
            objDB.ExecuteQuery()
            objDB.DbTransCommit()
            objDB.CloseConnection()
            Dim objAttComp As New ImageComp
            objAttComp.DeleteSingleFile("attachment", lnkAttachment.Text)
            LoadAnnouncement(lblAnnouncementUID.Text)
        Catch ex As Exception
            If objDB.dbVariable.objConn.State = Data.ConnectionState.Open Then
                objDB.DbTransRollback()
                objDB.CloseConnection()
            End If
            lblMsgError.Text = ex.Message
            divError.Visible = True
            Exit Sub
        Finally
            If (objDB IsNot Nothing) Then
                objDB.CloseConnection()
            End If
        End Try
    End Sub

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSearch.Click
        LoadChklistStaff()
        mpeToListEntry.Show()
    End Sub

    Private Sub LoadchklistStaff()
        Dim TempDT As New Data.DataTable
        Dim objDB As New Database(AppSettings("datasource"), AppSettings("database"), AppSettings("username"), AppSettings("password"), AppSettings("timeout"), AppSettings("pooling"))
        Try
            objDB.OpenConnection()

            objDB.dbVariable.SQLString = "SELECT StaffId, Name FROM AW_Staff WHERE StatusDelete = 0 ORDER BY Name"
            objDB.FillData(TempDT, "AW_Staff", Database.SQLCommandType.NormalString)
            objDB.CloseConnection()
        Catch ex As Exception

        Finally
            If (objDB IsNot Nothing) Then
                objDB.CloseConnection()
            End If
        End Try

        If TempDT.Rows.Count > 0 Then
            chklistStaff.DataSource = TempDT
            chklistStaff.DataTextField = "Name"
            chklistStaff.DataValueField = "StaffId"
            chklistStaff.DataBind()
        End If

        If lblTolist.Text <> "" Then
            Dim arrToList() As String
            arrToList = lblTolist.Text.Split("«")
            For Each ToId As String In arrToList
                For Each item As ListItem In chklistStaff.Items
                    If item.Value = ToId Then
                        item.Selected = True
                        Exit For
                    End If
                Next
            Next
        End If
    End Sub

    Protected Sub btnSelect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSelect.Click
        Dim strSelected As String = String.Empty
        Dim strSelectedValue As String = String.Empty
        For Each item As ListItem In chklistStaff.Items
            If item.Selected Then
                If strSelected = "" Then
                    strSelected = item.Text
                Else
                    strSelected += ", " & item.Text
                End If
                If strSelectedValue = "" Then
                    strSelectedValue = item.Value
                Else
                    strSelectedValue += "«" & item.Value
                End If
            End If
        Next
        lblTolist.Text = strSelectedValue
        txtTolist.Text = strSelected
    End Sub

    Protected Sub btnSelectAll_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSelectAll.Click
        Dim strSelected As String = String.Empty
        Dim strSelectedValue As String = String.Empty
        For Each item As ListItem In chklistStaff.Items
            If strSelected = "" Then
                strSelected = item.Text
            Else
                strSelected += ", " & item.Text
            End If
            If strSelectedValue = "" Then
                strSelectedValue = item.Value
            Else
                strSelectedValue += "«" & item.Value
            End If
        Next
        lblTolist.Text = strSelectedValue
        txtTolist.Text = strSelected
    End Sub

    Protected Sub btnBack_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnBack.Click
        If Session("Back") Is Nothing Then
            Response.Redirect("AnnouncementList.aspx")
        Else
            Dim strBack As String = Session("Back").ToString
            Dim arr() As String = strBack.Split("ڡ")
            Response.Redirect(arr(0).ToString)
        End If
    End Sub
End Class
